JSX vs. Templates
(Optional lesson)
JSX is sometimes compared to template languages, like Handlebars or EJS or Pug. There's an important distinction between these two concepts, though. In this lesson, we're going to see how JSX is a bit of a different beast.
Comparing JSX to template languages
For comparison, let's imagine we have a Handlebars template like this:
<div> {{#if user}} <h1>{{user.name}}</h1> {{/if}}</div>
The Handlebars library includes a JavaScript function that takes a Handlebars template and some data, and produces an HTML string. For example, if there's a user by the name of Sujata, we'll wind up with the following string: "<div><h1>Sujata</h1></div>"
.
Template languages also generally have a custom , with special syntax and keywords. In the example above, #if
is a built-in helper that will conditionally render some children. Another helper, #each
, will iterate through an array.
Here's the important distinction: all of that dynamic / custom stuff happens when we compile the template.
With React, we're compiling JSX to JS. We aren't resolving any of the dynamic stuff yet.
We'll learn more about conditional rendering soon, but as a quick preview, here’s how we'd do the same thing in JSX:
<div> {user && <h1>{user.name}</h1>}</div>
And here's what it compiles to:
React.createElement( 'div', {}, user && React.createElement( 'h1', {}, { children: user.name } ));
Notice that our condition hasn't been resolved yet. We don't know if we have a user yet or not.
Template languages are their own special thing. They invent custom syntax like {{#if}}
. In essence, you have to learn an entirely separate language, learn its subtle differences from JavaScript.
JSX is actually a very thin layer of abstraction. It isn't an entirely separate language. We use plain ol’ JavaScript to manage conditionals and iteration. And this means you only need to understand one language, JavaScript, to use it effectively.
It took me a while to wrap my head around this distinction. Here's another way to put it:
- Template languages turn the markup you write into HTML. This means they need to invent a custom mini-language to do dynamic things, since HTML doesn't have these things built-in.
- JSX turns the markup you write into JavaScript. It "forwards along" any logic you include, without resolving it.
Personally, I prefer the JSX approach. I like only having to understand 1 language.
Another benefit: we have the full power of JavaScript available as we write our markup! Template languages tend to be pretty narrow in their scope, and so they won't let you do things like filter an array to only select certain items. Instead of being limited to a small number of helpers like {{#each}}
, we have all of the JS methods available to us, like .filter
, .slice
, and .reduce
.